package main.java.service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;

@Service("resourceService")
public class ResourceService {
	@Autowired
	WebApplicationContext webApplicationContext;
	
	private String webappRootPath = null;				//��ǰ��Ŀ��Ŀ¼�ļ�ϵͳ·��
	private String webappRootUrl = null;					//��ǰ��Ŀ��URL��ַ
	
	/**
	 * get current webapp root path
	 * (i.e.  E:/eclipse_workspace/JMuners/)
	 * @return
	 * @throws IOException
	 */
	public String getCurrentWebappRootPath() throws IOException		{
		if(webappRootPath != null)		{
			return webappRootPath;
		}
		
		Resource resource = webApplicationContext.getResource("classpath:/");
		String rawPath = resource.getFile().getAbsolutePath();
		int end = rawPath.indexOf("WEB-INF\\classes");
		webappRootPath = new File(rawPath.substring(0, end)).toString()+'\\';		//��File���ʽ��ϵͳ·����ʽ
		webappRootPath = webappRootPath.replaceAll("\\\\", "/");		//��ʹ�÷�б�ܡ�/�����Լ���linux�ļ�ϵͳ·����ʽ
		return webappRootPath;
	}
	
	/**
	 * get current webapp root url
	 * (i.e. http://127.0.0.1/JMuners/)
	 * @return
	 * @throws IOException
	 */
	public String getCurrentWebappRootUrl() throws IOException		{
		if(webappRootUrl != null)		{
			return webappRootUrl;
		}
		
		Properties prop = getCurrentWebappProperties();
		webappRootUrl = prop.getProperty("jmuners.url")+prop.getProperty("jmuners.contextName")+'/';
		return webappRootUrl;
	}
	
	/**
	 * get current webapp properties
	 * @return
	 * @throws IOException
	 */
	public Properties getCurrentWebappProperties() throws IOException			{
		InputStream input = new BufferedInputStream(new FileInputStream(getCurrentWebappRootPath()+"WEB-INF\\JMuners.properties"));
		Properties prop = new Properties();
		prop.load(input);
		return prop;
	}
	
	/**
	 * generate a File object for a specific file 
	 * @param fileDirectory directory fragments
	 * @param fileName file's name
	 * @return
	 */
	public File genFile(String fileName, String... fileDirectory)		{
		return genFile(fileName, Arrays.asList(fileDirectory));
	}
	
	/**
	 * generate a File object for a specific file 
	 * @param fileDirectory directory fragments
	 * @param fileName file's name
	 * @return
	 */
	public File genFile(String fileName, List<String> fileDirectory)		{
		//assemble directory string fragments
		StringBuilder directory = new StringBuilder();
		for(String s : fileDirectory)			{
			directory.append(s).append("/");
		}
		
		//create file path recursively
		new File(directory.toString()).mkdirs();

		return new File(directory.toString()+fileName);
	}
	
	/**
	 * transfer between file path and url path
	 * @param transmitter
	 * @return
	 */
	public String transFileAndUrlPath(String transmitter)			{
		String urlPath = null;
		String filePath = null;
		try {
			urlPath = replaceWithBackSlash(getCurrentWebappRootUrl());
			filePath = replaceWithBackSlash(getCurrentWebappRootPath());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//transfer between url and file path.
		String oppositePath = null;
		transmitter = replaceWithBackSlash(transmitter);
		if(transmitter.startsWith(urlPath))			{
			oppositePath = filePath + transmitter.substring(urlPath.length());
		}
		else if(transmitter.startsWith(filePath))		{
			oppositePath = urlPath + transmitter.substring(filePath.length()); 
		}
		else		{
			throw new RuntimeException("judking## ResourceService: transFileAndUrlPath: parameter starts with neither urlPath or filePath");
		}
		return oppositePath;
	}
	
	public String replaceWithBackSlash(String str)		{
		return str.replaceAll("\\\\", "/");
	}
	
	/**
	 * get fileName prefix 
	 * @param fileName
	 * @return
	 */
	public String getFileNamePrefix(String fileName)			{
		int end = fileName.lastIndexOf(".");
		return  fileName.substring(0, end);
	}
	
	/**
	 * get fileName suffix
	 * @param fileName
	 * @return
	 */
	public String getFileNameSuffix(String fileName)		{
		int end = fileName.lastIndexOf(".");
		return fileName.substring(end+1);
	}
	
	/**
	 * write data to target file
	 * @param target
	 * @param data
	 * @throws IOException 
	 */
	public void writeToFile(File target, byte[] data, boolean append) throws IOException		{
		BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(target, append));
		output.write(data);
		output.flush();
		output.close();
	}
}
